<template>
    <div class="edit-photo-container">
        <img class="image" :src="previewImage" ref="image"/>
        <van-nav-bar
            class="tool-bar"
            left-text="取消"
            right-text="确定"
            @click-left="$emit('close')"
            @click-right="photoConfirm"
        />
    </div>
</template>

<script>
import 'cropperjs/dist/cropper.css';
import Cropper from 'cropperjs';
import * as Api from 'api/common';

export default {
    name: 'edit-photo',
    components: {
    },
    props: {
        file: {
            required: true,
            default () {
                return null;
            }
        }
    },
    // 监控data中的数据变化
    watch: {
        file: {
            handler (val, oldVal) {
                this.previewImage = window.URL.createObjectURL(val);
                if (oldVal) { // 后续选择其余图片时触发此处
                    this.cropper.destroy();
                    this.$nextTick(() => {
                        this.initCropper();
                    });
                }
            },
            immediate: true
        }
    },
    // 定义属性
    data () {
        return {
            previewImage: null,
            cropper: null
        };
    },
    // 计算属性，会监听依赖属性值随之变化
    computed: {
    },
    // 方法集合
    methods: {
        async photoConfirm () {
            this.$toast.loading({
                message: '保存中...',
                forbidclick: true,
                duration: 0
            });
            let data = new FormData();
            const photoBlob = await this.getCroppedCanvas();
            data.append('photo', photoBlob);
            const res = await Api.reqDev('/v1_0/user/photo', 'patch', { data });
            this.$toast.clear();
            if (res.message === 'OK') {
                this.$emit('update-img', res.data.photo);
                this.$toast.success('修改成功');
            }
            this.$emit('close');
        },
        initCropper () {
            const image = this.$refs.image;
            this.cropper = new Cropper(image, {
                viewMode: 1,
                dragMode: 'move',
                aspectRatio: 1,
                cropBoxMovable: false,
                cropBoxResizable: false,
                background: false,
                movable: true
            });
        },
        getCroppedCanvas () {
            return new Promise(resolve => {
                this.cropper.getCroppedCanvas().toBlob(blob => {
                    console.log(blob);
                    resolve(blob);
                });
            });
        }
    },
    // 生命周期 - 创建完成（可以访问当前this实例）
    created () {
        // this.previewImage = window.URL.createObjectURL(this.file);
    },
    // 生命周期 - 挂载完成（可以访问DOM元素）
    mounted () {
        // 第一次选择到图片时触发此处
        this.initCropper();
    }
};
</script>

<style lang='less' scoped>
.edit-photo-container {
    .image {
        display: block;
        max-width: 100%;
    }
    .tool-bar {
        position: fixed;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: unset;
    }
}
</style>
